package com.dayuanit.dy16.atm.service.impl;

import com.dayuanit.dy16.atm.dto.MessageDTO;
import com.dayuanit.dy16.atm.entity.Message;
import com.dayuanit.dy16.atm.holder.PageHolder;
import com.dayuanit.dy16.atm.mapper.MessageMapper;
import com.dayuanit.dy16.atm.service.IMessageService;
import com.dayuanit.dy16.atm.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MessageServiceImpl implements IMessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Override
    public PageHolder<MessageDTO> queryMessages(long userId, int currentPage) {
        int total = messageMapper.countMessage(userId);

        PageHolder<MessageDTO> pageHolder = PageHolder.build(total, currentPage);

        List<Message> messages = messageMapper.listMessage(userId, pageHolder.offset(), pageHolder.getPageSize());

        List<MessageDTO> dtos = new ArrayList<>(messages.size());
        for (Message message : messages) {
            MessageDTO messageDTO = new MessageDTO();
            dtos.add(messageDTO);

            messageDTO.setContext(message.getContext());
            messageDTO.setMsgId(message.getId());
            messageDTO.setMsgType(message.getMsgType());
            messageDTO.setStatus(message.getStatus());
            messageDTO.setCreateTime(DateUtils.date2String(message.getCreateTime()));
        }

        pageHolder.setData(dtos);
        return pageHolder;
    }

    @Override
    public List<MessageDTO> unReadMsg(long userId) {
        List<Message> messages = messageMapper.listMsgByStatus(1, userId);
        List<MessageDTO> dtos = new ArrayList<>(messages.size());
        for (Message message : messages) {
            MessageDTO messageDTO = new MessageDTO();
            dtos.add(messageDTO);

            messageDTO.setContext(message.getContext());
            messageDTO.setMsgId(message.getId());
            messageDTO.setMsgType(message.getMsgType());
            messageDTO.setStatus(message.getStatus());
            messageDTO.setCreateTime(DateUtils.date2String(message.getCreateTime()));
        }
        return dtos;
    }
}
